#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash graphmap-0.3.0sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules csh time patch libatomic perl-Data-Dumper autoconf automake libtool numactl binutils systemd-devel valgrind flex wget

set -e
yum install zlib zlib-devel libstdc++-static libomp -y

cd $buildpath
wget -t 10 -c https://github.com/isovic/graphmap/archive/refs/tags/v0.3.0.tar.gz -O graphmap-0.3.0.tar.gz
wget -t 10 -c https://github.com/isovic/argparser/archive/d0dae52c3d1b029f65f3bf4f0cd671e88dbeb98f.zip
wget -t 10 -c https://github.com/isovic/seqlib/archive/6c00d87d8fa1012f815dcc5c547435ceb7485193.zip

tar -zxvf graphmap-0.3.0.tar.gz && rm -rf graphmap-0.3.0.tar.gz
unzip 6c00d87d8fa1012f815dcc5c547435ceb7485193.zip && rm -rf 6c00d87d8fa1012f815dcc5c547435ceb7485193.zip
unzip d0dae52c3d1b029f65f3bf4f0cd671e88dbeb98f.zip && rm -rf d0dae52c3d1b029f65f3bf4f0cd671e88dbeb98f.zip
cp -rf argparser-d0dae52c3d1b029f65f3bf4f0cd671e88dbeb98f/* graphmap-0.3.0/codebase/argumentparser/
cp -rf seqlib-6c00d87d8fa1012f815dcc5c547435ceb7485193/* graphmap-0.3.0/codebase/seqlib/

cd graphmap-0.3.0
sed -i '19c GCC  ?=clang++' Makefile
sed -i 's/ -ffreestanding//g' Makefile
sed -i '54s/-lgomp/-lomp/g' Makefile
sed -i '52s/-m64/-mabi=lp64/' Makefile
make -j$(nproc)

mkdir -p $installpath/graphmap-0.3.0 && cp -r $buildpath/graphmap-0.3.0/* $installpath/graphmap-0.3.0

cat>"$installpath/graphmap-0.3.0/graphmap_modulefiles"<<EOF
#%Module1.0
conflict graphmap
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set GRAPHMAP \$pwd
setenv GRAPHMAP \$GRAPHMAP
prepend-path PATH \$GRAPHMAP/bin/Linux-x64
EOF

rm -rf $buildpath/graphmap-0.3.0

